package cn.ibizlab.odoo.webapi.rest;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.math.BigInteger;
import java.util.HashMap;

import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSONObject;

import javax.servlet.ServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.beans.BeanCopier;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.HttpStatus;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.util.StringUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.access.prepost.PreAuthorize;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;

import cn.ibizlab.odoo.webapi.dto.*;
import cn.ibizlab.odoo.webapi.mapping.*;
import cn.ibizlab.odoo.core.odoo_sale.domain.Sale_order;
import cn.ibizlab.odoo.core.odoo_sale.service.ISale_orderService;
import cn.ibizlab.odoo.core.odoo_sale.filter.Sale_orderSearchContext;



import cn.ibizlab.odoo.core.odoo_sale.filter.Sale_order_lineSearchContext;
import cn.ibizlab.odoo.core.odoo_sale.domain.Sale_order_line;
import cn.ibizlab.odoo.core.odoo_sale.service.ISale_order_lineService;

@Slf4j
@Api(tags = {"Sale_order" })
@RestController("WebApi-sale_order")
@RequestMapping("")
public class Sale_orderResource {

    @Autowired
    private ISale_orderService sale_orderService;

    @Autowired
    @Lazy
    private Sale_orderMapping sale_orderMapping;

    @Autowired
    private ISale_order_lineService sale_order_lineService;











    @PreAuthorize("hasPermission(#sale_order_id,'Update',{this.getEntity(),'ServiceApi'})")
    @ApiOperation(value = "更新数据", tags = {"Sale_order" },  notes = "更新数据")
	@RequestMapping(method = RequestMethod.PUT, value = "/sale_orders/{sale_order_id}")

    public ResponseEntity<Sale_orderDTO> update(@PathVariable("sale_order_id") Integer sale_order_id, @RequestBody Sale_orderDTO sale_orderdto) {
		Sale_order domain = sale_orderMapping.toDomain(sale_orderdto);
        domain.setId(sale_order_id);
		sale_orderService.update(domain);
		Sale_orderDTO dto = sale_orderMapping.toDto(domain);
        return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @PreAuthorize("hasPermission(#sale_order_id,'Update',{this.getEntity(),'ServiceApi'})")
    @ApiOperation(value = "UpdateBatch", tags = {"Sale_order" },  notes = "UpdateBatch")
	@RequestMapping(method = RequestMethod.PUT, value = "/sale_orders/batch")
    public ResponseEntity<Boolean> updateBatch(@RequestBody List<Sale_orderDTO> sale_orderdtos) {
        sale_orderService.updateBatch(sale_orderMapping.toDomain(sale_orderdtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }




    @PreAuthorize("hasPermission(#sale_order_id,'Get',{this.getEntity(),'ServiceApi'})")
    @ApiOperation(value = "获取数据", tags = {"Sale_order" },  notes = "获取数据")
	@RequestMapping(method = RequestMethod.GET, value = "/sale_orders/{sale_order_id}")
    public ResponseEntity<Sale_orderDTO> get(@PathVariable("sale_order_id") Integer sale_order_id) {
        Sale_order domain = sale_orderService.get(sale_order_id);
        Sale_orderDTO dto = sale_orderMapping.toDto(domain);
        return ResponseEntity.status(HttpStatus.OK).body(dto);
    }




    @ApiOperation(value = "Save", tags = {"Sale_order" },  notes = "Save")
	@RequestMapping(method = RequestMethod.POST, value = "/sale_orders/save")
    public ResponseEntity<Boolean> save(@RequestBody Sale_orderDTO sale_orderdto) {
        return ResponseEntity.status(HttpStatus.OK).body(sale_orderService.save(sale_orderMapping.toDomain(sale_orderdto)));
    }

    @ApiOperation(value = "SaveBatch", tags = {"Sale_order" },  notes = "SaveBatch")
	@RequestMapping(method = RequestMethod.POST, value = "/sale_orders/savebatch")
    public ResponseEntity<Boolean> saveBatch(@RequestBody List<Sale_orderDTO> sale_orderdtos) {
        sale_orderService.saveBatch(sale_orderMapping.toDomain(sale_orderdtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }




    @ApiOperation(value = "CheckKey", tags = {"Sale_order" },  notes = "CheckKey")
	@RequestMapping(method = RequestMethod.POST, value = "/sale_orders/checkkey")
    public ResponseEntity<Boolean> checkKey(@RequestBody Sale_orderDTO sale_orderdto) {
        return  ResponseEntity.status(HttpStatus.OK).body(sale_orderService.checkKey(sale_orderMapping.toDomain(sale_orderdto)));
    }




    @PreAuthorize("hasPermission('Remove',{#sale_order_id,{this.getEntity(),'ServiceApi'}})")
    @ApiOperation(value = "删除数据", tags = {"Sale_order" },  notes = "删除数据")
	@RequestMapping(method = RequestMethod.DELETE, value = "/sale_orders/{sale_order_id}")

    public ResponseEntity<Boolean> remove(@PathVariable("sale_order_id") Integer sale_order_id) {
         return ResponseEntity.status(HttpStatus.OK).body(sale_orderService.remove(sale_order_id));
    }

    @ApiOperation(value = "RemoveBatch", tags = {"Sale_order" },  notes = "RemoveBatch")
	@RequestMapping(method = RequestMethod.DELETE, value = "/sale_orders/batch")
    public ResponseEntity<Boolean> removeBatch(@RequestBody List<Integer> ids) {
        sale_orderService.removeBatch(ids);
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }




    @ApiOperation(value = "获取草稿数据", tags = {"Sale_order" },  notes = "获取草稿数据")
	@RequestMapping(method = RequestMethod.GET, value = "/sale_orders/getdraft")
    public ResponseEntity<Sale_orderDTO> getDraft() {
        return ResponseEntity.status(HttpStatus.OK).body(sale_orderMapping.toDto(sale_orderService.getDraft(new Sale_order())));
    }







    @PreAuthorize("hasPermission('','Create',{this.getEntity(),'ServiceApi'})")
    @ApiOperation(value = "建立数据", tags = {"Sale_order" },  notes = "建立数据")
	@RequestMapping(method = RequestMethod.POST, value = "/sale_orders")

    public ResponseEntity<Sale_orderDTO> create(@RequestBody Sale_orderDTO sale_orderdto) {
        Sale_order domain = sale_orderMapping.toDomain(sale_orderdto);
		sale_orderService.create(domain);
        Sale_orderDTO dto = sale_orderMapping.toDto(domain);
		return ResponseEntity.status(HttpStatus.OK).body(dto);
    }
    @PreAuthorize("hasPermission('','Create',{this.getEntity(),'ServiceApi'})")
    @ApiOperation(value = "createBatch", tags = {"Sale_order" },  notes = "createBatch")
	@RequestMapping(method = RequestMethod.POST, value = "/sale_orders/batch")
    public ResponseEntity<Boolean> createBatch(@RequestBody List<Sale_orderDTO> sale_orderdtos) {
        sale_orderService.createBatch(sale_orderMapping.toDomain(sale_orderdtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','crm-Sale_order-Default-all')")
	@ApiOperation(value = "fetch默认查询", tags = {"Sale_order" } ,notes = "fetch默认查询")
    @RequestMapping(method= RequestMethod.GET , value="/sale_orders/fetchdefault")
	public ResponseEntity<List<Sale_orderDTO>> fetchDefault(Sale_orderSearchContext context) {
        Page<Sale_order> domains = sale_orderService.searchDefault(context) ;
        List<Sale_orderDTO> list = sale_orderMapping.toDto(domains.getContent());
        return ResponseEntity.status(HttpStatus.OK)
                .header("x-page", String.valueOf(context.getPageable().getPageNumber()))
                .header("x-per-page", String.valueOf(context.getPageable().getPageSize()))
                .header("x-total", String.valueOf(domains.getTotalElements()))
                .body(list);
	}

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','crm-Sale_order-Default-all')")
	@ApiOperation(value = "search默认查询", tags = {"Sale_order" } ,notes = "search默认查询")
    @RequestMapping(method= RequestMethod.POST , value="/sale_orders/searchdefault")
	public ResponseEntity<Page<Sale_orderDTO>> searchDefault(@RequestBody Sale_orderSearchContext context) {
        Page<Sale_order> domains = sale_orderService.searchDefault(context) ;
	    return ResponseEntity.status(HttpStatus.OK)
                .body(new PageImpl(sale_orderMapping.toDto(domains.getContent()), context.getPageable(), domains.getTotalElements()));
	}



    @ApiOperation(value = "更新数据ByRes_partner", tags = {"Sale_order" },  notes = "更新数据ByRes_partner")
	@RequestMapping(method = RequestMethod.PUT, value = "/res_partners/{res_partner_id}/sale_orders/{sale_order_id}")

    public ResponseEntity<Sale_orderDTO> updateByRes_partner(@PathVariable("res_partner_id") Integer res_partner_id, @PathVariable("sale_order_id") Integer sale_order_id, @RequestBody Sale_orderDTO sale_orderdto) {
        Sale_order domain = sale_orderMapping.toDomain(sale_orderdto);
        domain.setPartnerId(res_partner_id);
        domain.setId(sale_order_id);
		sale_orderService.update(domain);
        Sale_orderDTO dto = sale_orderMapping.toDto(domain);
        return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @ApiOperation(value = "UpdateBatchByRes_partner", tags = {"Sale_order" },  notes = "UpdateBatchByRes_partner")
	@RequestMapping(method = RequestMethod.PUT, value = "/res_partners/{res_partner_id}/sale_orders/batch")
    public ResponseEntity<Boolean> updateBatchByRes_partner(@PathVariable("res_partner_id") Integer res_partner_id, @RequestBody List<Sale_orderDTO> sale_orderdtos) {
        List<Sale_order> domainlist=sale_orderMapping.toDomain(sale_orderdtos);
        for(Sale_order domain:domainlist){
            domain.setPartnerId(res_partner_id);
        }
        sale_orderService.updateBatch(domainlist);
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @ApiOperation(value = "获取数据ByRes_partner", tags = {"Sale_order" },  notes = "获取数据ByRes_partner")
	@RequestMapping(method = RequestMethod.GET, value = "/res_partners/{res_partner_id}/sale_orders/{sale_order_id}")
    public ResponseEntity<Sale_orderDTO> getByRes_partner(@PathVariable("res_partner_id") Integer res_partner_id, @PathVariable("sale_order_id") Integer sale_order_id) {
        Sale_order domain = sale_orderService.get(sale_order_id);
        Sale_orderDTO dto = sale_orderMapping.toDto(domain);
        return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @ApiOperation(value = "SaveByRes_partner", tags = {"Sale_order" },  notes = "SaveByRes_partner")
	@RequestMapping(method = RequestMethod.POST, value = "/res_partners/{res_partner_id}/sale_orders/save")
    public ResponseEntity<Boolean> saveByRes_partner(@PathVariable("res_partner_id") Integer res_partner_id, @RequestBody Sale_orderDTO sale_orderdto) {
        Sale_order domain = sale_orderMapping.toDomain(sale_orderdto);
        domain.setPartnerId(res_partner_id);
        return ResponseEntity.status(HttpStatus.OK).body(sale_orderService.save(domain));
    }

    @ApiOperation(value = "SaveBatchByRes_partner", tags = {"Sale_order" },  notes = "SaveBatchByRes_partner")
	@RequestMapping(method = RequestMethod.POST, value = "/res_partners/{res_partner_id}/sale_orders/savebatch")
    public ResponseEntity<Boolean> saveBatchByRes_partner(@PathVariable("res_partner_id") Integer res_partner_id, @RequestBody List<Sale_orderDTO> sale_orderdtos) {
        List<Sale_order> domainlist=sale_orderMapping.toDomain(sale_orderdtos);
        for(Sale_order domain:domainlist){
             domain.setPartnerId(res_partner_id);
        }
        sale_orderService.saveBatch(domainlist);
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @ApiOperation(value = "CheckKeyByRes_partner", tags = {"Sale_order" },  notes = "CheckKeyByRes_partner")
	@RequestMapping(method = RequestMethod.POST, value = "/res_partners/{res_partner_id}/sale_orders/checkkey")
    public ResponseEntity<Boolean> checkKeyByRes_partner(@PathVariable("res_partner_id") Integer res_partner_id, @RequestBody Sale_orderDTO sale_orderdto) {
        return  ResponseEntity.status(HttpStatus.OK).body(sale_orderService.checkKey(sale_orderMapping.toDomain(sale_orderdto)));
    }

    @ApiOperation(value = "删除数据ByRes_partner", tags = {"Sale_order" },  notes = "删除数据ByRes_partner")
	@RequestMapping(method = RequestMethod.DELETE, value = "/res_partners/{res_partner_id}/sale_orders/{sale_order_id}")

    public ResponseEntity<Boolean> removeByRes_partner(@PathVariable("res_partner_id") Integer res_partner_id, @PathVariable("sale_order_id") Integer sale_order_id) {
		return ResponseEntity.status(HttpStatus.OK).body(sale_orderService.remove(sale_order_id));
    }

    @ApiOperation(value = "RemoveBatchByRes_partner", tags = {"Sale_order" },  notes = "RemoveBatchByRes_partner")
	@RequestMapping(method = RequestMethod.DELETE, value = "/res_partners/{res_partner_id}/sale_orders/batch")
    public ResponseEntity<Boolean> removeBatchByRes_partner(@RequestBody List<Integer> ids) {
        sale_orderService.removeBatch(ids);
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @ApiOperation(value = "获取草稿数据ByRes_partner", tags = {"Sale_order" },  notes = "获取草稿数据ByRes_partner")
    @RequestMapping(method = RequestMethod.GET, value = "/res_partners/{res_partner_id}/sale_orders/getdraft")
    public ResponseEntity<Sale_orderDTO> getDraftByRes_partner(@PathVariable("res_partner_id") Integer res_partner_id) {
        Sale_order domain = new Sale_order();
        domain.setPartnerId(res_partner_id);
        return ResponseEntity.status(HttpStatus.OK).body(sale_orderMapping.toDto(sale_orderService.getDraft(domain)));
    }

    @ApiOperation(value = "建立数据ByRes_partner", tags = {"Sale_order" },  notes = "建立数据ByRes_partner")
	@RequestMapping(method = RequestMethod.POST, value = "/res_partners/{res_partner_id}/sale_orders")

    public ResponseEntity<Sale_orderDTO> createByRes_partner(@PathVariable("res_partner_id") Integer res_partner_id, @RequestBody Sale_orderDTO sale_orderdto) {
        Sale_order domain = sale_orderMapping.toDomain(sale_orderdto);
        domain.setPartnerId(res_partner_id);
		sale_orderService.create(domain);
        Sale_orderDTO dto = sale_orderMapping.toDto(domain);
		return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @ApiOperation(value = "createBatchByRes_partner", tags = {"Sale_order" },  notes = "createBatchByRes_partner")
	@RequestMapping(method = RequestMethod.POST, value = "/res_partners/{res_partner_id}/sale_orders/batch")
    public ResponseEntity<Boolean> createBatchByRes_partner(@PathVariable("res_partner_id") Integer res_partner_id, @RequestBody List<Sale_orderDTO> sale_orderdtos) {
        List<Sale_order> domainlist=sale_orderMapping.toDomain(sale_orderdtos);
        for(Sale_order domain:domainlist){
            domain.setPartnerId(res_partner_id);
        }
        sale_orderService.createBatch(domainlist);
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

	@ApiOperation(value = "fetch默认查询ByRes_partner", tags = {"Sale_order" } ,notes = "fetch默认查询ByRes_partner")
    @RequestMapping(method= RequestMethod.GET , value="/res_partners/{res_partner_id}/sale_orders/fetchdefault")
	public ResponseEntity<List<Sale_orderDTO>> fetchSale_orderDefaultByRes_partner(@PathVariable("res_partner_id") Integer res_partner_id,Sale_orderSearchContext context) {
        context.setN_partner_id_eq(res_partner_id);
        Page<Sale_order> domains = sale_orderService.searchDefault(context) ;
        List<Sale_orderDTO> list = sale_orderMapping.toDto(domains.getContent());
	    return ResponseEntity.status(HttpStatus.OK)
                .header("x-page", String.valueOf(context.getPageable().getPageNumber()))
                .header("x-per-page", String.valueOf(context.getPageable().getPageSize()))
                .header("x-total", String.valueOf(domains.getTotalElements()))
                .body(list);
	}

	@ApiOperation(value = "search默认查询ByRes_partner", tags = {"Sale_order" } ,notes = "search默认查询ByRes_partner")
    @RequestMapping(method= RequestMethod.POST , value="/res_partners/{res_partner_id}/sale_orders/searchdefault")
	public ResponseEntity<Page<Sale_orderDTO>> searchSale_orderDefaultByRes_partner(@PathVariable("res_partner_id") Integer res_partner_id, @RequestBody Sale_orderSearchContext context) {
        context.setN_partner_id_eq(res_partner_id);
        Page<Sale_order> domains = sale_orderService.searchDefault(context) ;
	    return ResponseEntity.status(HttpStatus.OK)
                .body(new PageImpl(sale_orderMapping.toDto(domains.getContent()), context.getPageable(), domains.getTotalElements()));
	}


    /**
     * 用户权限校验
     * @return
     */
	public Sale_order getEntity(){
        return new Sale_order();
    }

}
